package com.daJiao.controller.api;

import com.daJiao.domain.WrapMapper;
import com.daJiao.domain.Wrapper;
import com.daJiao.properties.WxMpProperties;
import com.daJiao.service.SysSubscribeUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * <p>Title:      WxRedirectController. </p>
 * <p>Description 微信用户信息 </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:    医百科技有限公司 </p>
 *
 * @author         <a href="yangwensheng@100doc.com.cn"/>杨文生</a>
 * @since      2021/2/27 18:18
 */
@RestController
@RequestMapping("/wx")
@Api(tags = "微信管理(API)", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Slf4j
public class ApiWxController {

    @Resource
    private  WxMpService wxService;

    @Resource
    private WxMpProperties wxMpProperties;

    @Resource
    private SysSubscribeUserService sysSubscribeUserService;

    @GetMapping("/getAccessToken/{code}")
    @ApiOperation(notes = "获取accessToken", httpMethod = "GET", value = "获取accessToken")
    public Wrapper<WxOAuth2AccessToken> getAccessToken(@PathVariable("code") String code) throws WxErrorException {
        WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code);
        sysSubscribeUserService.saveSubscribeUserSample(accessToken.getOpenId());
        return WrapMapper.ok(accessToken);
    }


    @GetMapping("/getWxUserInfo/{accessToken}/{openId}")
    @ApiOperation(notes = "获取微信用户信息", httpMethod = "GET", value = "获取微信用户信息")
    public Wrapper<WxOAuth2UserInfo> getWxUserInfo(@PathVariable("accessToken") String accessToken, @PathVariable("openId") String openId) throws WxErrorException {
        WxOAuth2AccessToken wxoAuth2AccessToken = new WxOAuth2AccessToken();
        wxoAuth2AccessToken.setAccessToken(accessToken);
        wxoAuth2AccessToken.setOpenId(openId);
        return WrapMapper.ok(wxService.getOAuth2Service().getUserInfo(wxoAuth2AccessToken, null));
    }


    @PostMapping("/getJsapiTicket")
    @ApiOperation(notes = "获取签名(JSAPI)", httpMethod = "POST", value = "获取签名(JSAPI)")
    public Wrapper<WxJsapiSignature> getJsapiTicket(@RequestBody String url) throws WxErrorException {
        WxJsapiSignature jsapiSignature = this.wxService.switchoverTo(wxMpProperties.getConfigs().get(0).getAppId()).createJsapiSignature(url);
        log.info("jsapiSignature={}",jsapiSignature);
        String jsapiTicket = this.wxService.getJsapiTicket(true);
        log.info("===> jsapiTicket={}",jsapiTicket);
        return WrapMapper.ok(jsapiSignature);
    }
}
